package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.ISetmealDishService;
import com.itheima.reggie.service.ISetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private ISetmealDishService setmealDishService;

    @Autowired
    private ISetmealService setmealService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     *添加套餐
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下,所有的缓存数据
    @PostMapping
    public R<String> saveSetmealDto(@RequestBody SetmealDto setmealDto){

        //1、保存套餐数据到 setmeal表中 ： SetmealMapper

        setmealService.save(setmealDto);
        //2、从前端获取套餐中SetmealDishes的数据
        //2.1 获取当前套餐的菜品列表
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();

        //
        //ArrayList<SetmealDish> list = new ArrayList<>();
        //2.2 循环遍历，获取每一个套餐菜品数据 setmealDish
        for (SetmealDish dish : dishes) {
            //2.3 获取套餐id，并set到setmealDish中
            Long dishId = setmealDto.getId();
            dish.setSetmealId(dishId);
            //list.add(dish);
        }

        /*dishes.stream().map((item) ->{
            Long id = setmealDto.getId();
            item.setSetmealId(id);
            return item;
        }).collect(Collectors.toList());*/
        //2.4 保存套餐菜品数据 setmealDish
        setmealDishService.saveBatch(dishes);
        return R.success("新增套餐成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){

        Page<Setmeal> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Setmeal> qw =new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        //qw.eq(Setmeal::getStatus,1);
        qw.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo,qw);

        return R.success(pageInfo);
    }

    /**
     * 逻辑删除套餐,如果是启售状态 ,不能删除
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下,所有的缓存数据
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){

        //1、判断当前要删除的套餐是否处于售卖状态，如果是，不允许删除
        // select count(*) from setmeal where id in (1,2,3) and status = 1
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.in(Setmeal::getId,ids).eq(Setmeal::getStatus,1);
        int count = setmealService.count(qw);
        System.out.println("起售的套餐数量"+count);
        if(count>0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }

        //2、删除套餐： delete from setmeal where id in (1,2,3)
        setmealService.removeByIds(ids);

        //3、删除套餐对应的菜品数据：delete from setmeal_dish where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lqw);
        return R.success("套餐删除成功");
    }

    /**
     * 套餐启售停售
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下,所有的缓存数据
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,
                                  @RequestParam List<Long> ids){
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("操作成功");
    }

    /**
     * 回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){

        //1、根据套餐id查询套餐数据 select * from setmeal where id =?

        Setmeal setmeal = setmealService.getById(id);
        //2、根据套餐id查询套餐对应的菜品数据 select * from setmeal_dish where setmeal_id = ?
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId,setmeal.getId());
        List<SetmealDish> list = setmealDishService.list(qw);
        //3、将套餐 setmeal 和套餐菜品集合 setmealDishList 数据封装到 SetmealDto并返回
        // 3.0 首先new一个SetmealDto对象
        SetmealDto setmealDto = new SetmealDto();

        // 3.1、BeanUtils.copyProperties() 拷贝setmeal到setmealDto中
        BeanUtils.copyProperties(setmeal,setmealDto);

        // 3.2、将setmealDishList 设置到 setmealDto中
        setmealDto.setSetmealDishes(list);

        //4、返回 setmealDto
        return R.success(setmealDto);


    }

    /**
     * 修改数据(套餐菜品先删除后修改)
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下,所有的缓存数据
    @PutMapping("")
    public R<String> update(@RequestBody SetmealDto setmealDto){

        // 1、修改套餐setmeal表的数据
        setmealService.updateById(setmealDto);
        //取出菜品id Long setmealId = setmealDto.getId();
        // 2、修改套餐的菜品数据 如何完成？？
        // 2.1 先删除原有的菜品数据: delete from SetmealDish where SetmealDish_id = ?;
        LambdaQueryWrapper<SetmealDish> qw =new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(qw);
        // 2.2 添加套餐菜品数据 List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
        return R.success("修改菜品成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key="#setmeal.categoryId + '::' +#setmeal.status")
    public R<List<Setmeal>> getSetmeal(Setmeal setmeal){

        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        qw.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());

        List<Setmeal> list = setmealService.list(qw);
        return R.success(list);
    }
}
